package com.gcxy.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.gcxy.entity.Role;
import com.gcxy.entity.User;
import com.gcxy.service.ResourceRoleService;
import com.gcxy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author pep7chiao
 * @date 2024/7/6
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private ResourceRoleService resourceRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据当前用户名到数据库中进行查询
        User user = userService.getUserByUserName(username);
        if (user != null) {
            // 设置当前用户的角色
            List<Role> roles = userService.getRoles(user.getId());
            user.setRoles(roles);
            //设置当前用户的资源
            if (ObjectUtils.isNotEmpty(roles)) {
                user.setResourceList(resourceRoleService.getResourceByRoleIds(roles.stream().map(Role::getId).collect(Collectors.toList())));
            }
            return user;
        }
        throw new UsernameNotFoundException("用户名或密码不正确");
    }
}
